<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @submit.native.prevent="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="项目名称" size="small">
            <el-input v-model="searchForm.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()"
                 v-if="roleType===0 || roleType===1 || roleType===2 || roleType===10 || roleType===13 ">添加
      </el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="1100px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="180px">
          <el-row>
            <el-col class="width350">
              <el-form-item prop="plotTime" label="日期" size="small">
                <el-date-picker
                  v-model="teamRow.plotTime"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                  style="width: 170px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item prop="projectName" label="项目名称" size="small">
                <el-input type="text" v-model="teamRow.projectName"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="工程号" size="small">
                <el-input type="text" v-model="teamRow.projectCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item prop="subproject" label="子项名称" size="small">
                <el-input type="text" v-model="teamRow.subproject"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="发件人" size="small">
                <el-input type="text" v-model="teamRow.sender"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col class="width350">
              <el-form-item label="水专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.waterContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="暖专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.warmContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="电专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.electricityContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="结构专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.structureContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="建筑专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.buildingContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="道路专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.roadContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="桥梁专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.bridgeContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="市政水专业设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.municipalContact"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="景观设计师联系电话" size="small">
                <el-input type="text" v-model="teamRow.landscapeContact"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-form-item label="审核进度" size="small">
            <el-button type="primary" icon="el-icon-plus" @click="addDrawingStageList()"></el-button>
          </el-form-item>
          <el-row v-if="hackReset" v-for="(item,index) in drawingStageList">
            <el-col class="width350">
              <el-form-item label="专业" size="small">
                <el-input type="text" v-model="item.profession"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="审核阶段" size="small">
                <el-select v-model="item.stage" placeholder="请选择">
                  <el-option
                    v-for="i in global.auditTypeList"
                    :key="i.value"
                    :label="i.label"
                    :value="i.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!--
            <el-col class="width350">
              <el-form-item prop="time" label="日期" size="small">
                <el-date-picker
                  v-model="item.time"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  style="width: 170px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            -->
            <el-col class="width350">
              <el-form-item label="合作人交时间" size="small">
                <el-input type="text" v-model="item.partnerTime"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="转发总工时间" size="small">
                <el-input type="text" v-model="item.forwardingTime"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="总工反馈时间" size="small">
                <el-input type="text" v-model="item.feedbackTime"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="反馈合作人时间" size="small">
                <el-input type="text" v-model="item.feedbackPartnerTime"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="是否出图" size="small">
                <el-radio-group v-model="item.isPicture">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item label="备注说明" size="small">
                <el-input type="text" v-model="item.remark"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="width350">
              <el-form-item size="small">
                <el-button type="danger" size="small" icon="el-icon-minus"
                           @click="delDrawingStageList(index)"></el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="250"
        v-if="roleType===0 || roleType===1 || roleType===2 || roleType===10 || roleType===13 "
      >
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editSchedule(scope.row)"
            type="text"
            size="small">
            阶段文件上传下载
          </el-button>
          <a v-if="scope.row.drawingPigeonhole" target="_blank" :href="GLOBAL.filePathUrl+encodeURI(scope.row.drawingPigeonhole)">下载</a>
          <el-button
            @click.native.prevent="editTeam(scope.row.auditId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog title="阶段文件上传下载" :visible.sync="scheduleVisible" width="600px">
      <input class="file" type="file" @change="fileChanged" ref="file"/>
      <table class="schedule_table">
        <tr>
          <td>图审阶段</td>
          <td>专业</td>
          <td>文件</td>
          <td>意见</td>
        </tr>
        <tr v-for="item in scheduleData">
          <td>图审{{item.stage}}</td>
          <td>{{item.profession}}</td>
          <td>
            <div v-if="item.filePath">
              <a @click="downloadFile(item,'files')">上传</a>
              <a target="_blank" :href="global.filePathUrl+encodeURI(item.filePath)">下载</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(`files${item.stageId}`)"
                           :percentage="precent" status="success"></el-progress>
            </div>
            <div v-else>
              <a style="color: red">X</a>
              <a @click="downloadFile(item,'files')">上传</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(`files${item.stageId}`)"
                           :percentage="precent" status="success"></el-progress>
            </div>
          </td>
          <td>
            <div v-if="item.opinionPath">
              <a @click="downloadFile(item,'opinion')">上传</a>
              <a target="_blank" :href="global.filePathUrl+encodeURI(item.opinionPath)">下载</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(`opinion${item.stageId}`)"
                           :percentage="precent" status="success"></el-progress>
            </div>
            <div v-else>
              <a style="color: red">X</a>
              <a @click="downloadFile(item,'opinion')">上传</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(`opinion${item.stageId}`)"
                           :percentage="precent" status="success"></el-progress>
            </div>
          </td>
        </tr>
      </table>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    insertDrawingAudit,
    updateDrawingAudit,
    selectDrawingAudit,
    delDrawingAudit,
    selectProjectName,
    downloadList,
    updateDrawingStage
  } from '@/api/chartdata'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'plotTime', label: '日期', width: '100', component: time },
          { prop: 'projectName', label: '项目名称', width: '300' },
          { prop: 'projectCode', label: '工程号', width: '100' },
          { prop: 'subproject', label: '子项名称', width: '150' },
          { prop: 'sender', label: '发件人', width: '150' },
          { prop: 'contact', label: '联系人及电话号码', width: '150' },
          { prop: 'remark', label: '备注说明', width: '200' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        scheduleForm: {},
        scheduleFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        scheduleLoading: true,
        dialogTitle: '新增院审数据',
        scheduleTitle: '',
        dialogType: 1,
        scheduleType: 1,
        teamRow: {},
        teamRowClear: {},
        margin: {},
        marginClear: {},
        tableData: [],
        scheduleData: {},
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        scheduleVisible: false,
        pca: pca,
        rules: {
          plotTime: [
            { required: true, message: '请选择日期', trigger: 'change' }
          ],
          projectCode: [
            { required: true, message: '请输入工程号', trigger: 'change' }
          ],
          projectName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          profession: [
            { required: true, message: '请选择专业', trigger: 'change' }
          ],
          drawingAmount: [
            { required: true, message: '请输入图纸数量', trigger: 'change' }
          ],
          forwardingTime: [
            { required: true, message: '请选择转发总工时间', trigger: 'change' }
          ]
        },
        scheduleRules: {
          professionType: [
            { required: true, message: '请选择专业类型', trigger: 'change' }
          ],
          auditType: [
            { required: true, message: '请选择审核进度', trigger: 'change' }
          ]
        },
        visible: false,
        drawingStageList: [],
        stageIds: [],
        hackReset: false, // 销毁重建组件
        scheduleRow: new FormData(),
        scheduleParams: {},
        precent: '',
        progress: ''
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      teamId() {
        return this.$store.state.user.teamId
      }
    },
    methods: {
      upLoad(upLoad, params, callback1, callback2) {
        upLoad(params, function(progressEvent) { // 原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
            callback1(progressEvent)
          }
        }).then(res => {
          callback2(res.data)
        }).catch(() => {
          this.$refs.file.value = ''
          this.progress = ''
        })
      },
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      scheduleFetchData() {
        downloadList(this.scheduleParams).then(response => {
          this.scheduleData = response.responseBody
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.hackReset = false // 销毁组件
        this.$nextTick(() => {
          this.hackReset = true // 重建组件
        })
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增院审数据'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        this.drawingStageList = []
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        this.$set(this.teamRow, 'teamId', this.teamId)
      },
      editTeam(auditId) {
        this.hackReset = false // 销毁组件
        this.$nextTick(() => {
          this.hackReset = true // 重建组件
        })
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改院审数据'
        this.stageIds = []
        this.dialogType = 0
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          auditId: auditId
        }
        selectDrawingAudit(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
          if (Array.isArray(this.teamRow.drawingStages)) {
            this.drawingStageList = []
            this.teamRow.drawingStages.forEach(value => {
              this.drawingStageList.push({
                stageId: value.stageId,
                auditId: value.auditId,
                profession: value.profession,
                stage: value.stage,
                partnerTime: value.partnerTime,
                forwardingTime: value.forwardingTime,
                feedbackTime: value.feedbackTime,
                isPicture: value.isPicture,
                feedbackPartnerTime: value.feedbackPartnerTime,
                remark: value.remark
              })
            })
          }
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('teamId', this.teamRow.teamId)
        params.append('projectCode', this.teamRow.projectCode || '')
        params.append('projectName', this.teamRow.projectName)
        params.append('subproject', this.teamRow.subproject || '')
        params.append('plotTime', this.teamRow.plotTime)
        params.append('sender', this.teamRow.sender || '')
        params.append('waterContact', this.teamRow.waterContact || '')
        params.append('warmContact', this.teamRow.warmContact || '')
        params.append('electricityContact', this.teamRow.electricityContact || '')
        params.append('structureContact', this.teamRow.structureContact || '')
        params.append('buildingContact', this.teamRow.buildingContact || '')
        params.append('roadContact', this.teamRow.roadContact || '')
        params.append('bridgeContact', this.teamRow.bridgeContact || '')
        params.append('municipalContact', this.teamRow.municipalContact || '')
        params.append('landscapeContact', this.teamRow.landscapeContact || '')
        params.append('remark', this.teamRow.remark || '')
        params.append('drawingStageList', JSON.stringify(this.drawingStageList))
        if (this.teamRow.file) {
          params.append('file', this.teamRow.file)
        }
        if (!this.dialogType) {
          params.append('auditId', this.teamRow.auditId)
          params.append('stageIds', this.stageIds.join(','))
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              insertDrawingAudit(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateDrawingAudit(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          auditId: scope.row.auditId,
          isDel: 1
        }
        delDrawingAudit(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            contractCode: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.contractCode
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'projectName', item.projectName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      getFile(event) {
        this.teamRow.file = event.target.files[0]
      },
      editSchedule(row) {
        this.scheduleVisible = true
        this.scheduleParams = {
          auditId: row.auditId
        }
        this.scheduleFetchData()
      },
      addDrawingStageList() {
        this.drawingStageList.push({
          stage: 1,
          isPicture: 2
        })
      },
      delDrawingStageList(index) {
        this.stageIds.push(this.drawingStageList[index].stageId)
        this.drawingStageList.splice(index, 1)
      },
      downloadFile(item, file) {
        this.scheduleRow = new FormData()
        this.scheduleRow.append('file', file)
        this.scheduleRow.append('stageId', item.stageId)
        this.scheduleRow.append('auditId', item.auditId)
        this.scheduleRow.append('profession', item.profession)
        this.$refs.file.click()
      },
      fileChanged() {
        this.progress = `${this.scheduleRow.get('file')}${this.scheduleRow.get('stageId')}`
        this.scheduleRow.append(this.scheduleRow.get('file'), this.$refs.file.files[0])
        this.scheduleRow.delete('file')
        this.upLoad(updateDrawingStage, this.scheduleRow, (res) => {
          const loaded = res.loaded
          const total = res.total
          this.$nextTick(() => {
            this.precent = (loaded / total) * 100
          })
        }, (res) => {
          this.$refs.file.value = ''
          this.progress = ''
          this.scheduleFetchData()
        })
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    .schedule_table {
      border-collapse: collapse;
      width: 550px;
      tr {
        td {
          width: 150px;
          padding: 10px 25px;
          border: 1px solid #99a9bf;
          text-align: center;
        }
      }
    }
    .file {
      display: none;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
